package com.zhiwang.planet.mvvm.viewmodel.loginv2

import android.annotation.SuppressLint
import android.content.Context
import android.graphics.Color
import android.net.wifi.WifiManager
import android.os.Build
import android.text.*
import android.text.style.ClickableSpan
import android.text.style.ForegroundColorSpan
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import com.zhiwang.planet.BuildConfig
import com.zhiwang.planet.aop.util.Throttle
import com.zhiwang.planet.event.LoginEvent
import com.zhiwang.planet.mvvm.model.RestApi
import com.zhiwang.planet.mvvm.model.request.RegisterRequest
import com.zhiwang.planet.mvvm.model.request.SmsReq
import com.zhiwang.planet.ui.PrivacyActivity
import com.zhiwang.planet.ui.WebViewActivity
import com.zhiwang.planet.ui.loginv2.WxLoginActivity
import com.zhiwang.planet.util.*
import com.zhiwang.planet.widget.ColdDownTextView
import io.reactivex.functions.Action
import io.reactivex.functions.Consumer
import org.greenrobot.eventbus.EventBus


open class RegisterViewModel constructor(): ViewModel() {

    val method = MutableLiveData("link")

    lateinit var errHandler: (Throwable) -> Unit

    lateinit var restApi: RestApi

    val agree = MutableLiveData<Boolean>(true)

    val username = MutableLiveData<String>()

    val smsCode = MutableLiveData<String>("")

    private var code: String = ""

    private var deviceId: String = ""

    fun setCode(c: String) {
        code = c
    }

    fun setDeviceId(imei: String) {
        deviceId = imei
    }

    lateinit var context: AppCompatActivity


    inner class UrlClickSpan constructor(val url: String) : ClickableSpan() {

        override fun onClick(widget: View?) {
            WebViewActivity.load(context, url)
        }

        override fun updateDrawState(ds: TextPaint) {
            super.updateDrawState(ds)
            ds.isUnderlineText = false
        }

    }

    inner class PageClickSpan : ClickableSpan() {
        override fun onClick(widget: View) {
            context.quickStartActivity(PrivacyActivity::class.java)
        }

        override fun updateDrawState(ds: TextPaint) {
            super.updateDrawState(ds)
            ds.isUnderlineText = false
        }

    }

    val agreementSpan = SpannableString("注册即同意《用户服务协议》《隐私协议》")
            .apply {
                setSpan(PageClickSpan(), 5, 14, Spanned.SPAN_INCLUSIVE_INCLUSIVE)
                setSpan(UrlClickSpan(Store.USER_AGREEMENT), 13, 19, Spanned.SPAN_INCLUSIVE_INCLUSIVE)
                setSpan(ForegroundColorSpan(Color.parseColor("#D78EFF")), 5, 14, Spannable.SPAN_INCLUSIVE_INCLUSIVE)
                setSpan(ForegroundColorSpan(Color.parseColor("#D78EFF")), 13, 19, Spannable.SPAN_INCLUSIVE_INCLUSIVE)
            }

    fun onAgreementClick() {
        agree.value = true
    }

    fun navAgreement(){
        WebViewActivity.load(context,Store.USER_AGREEMENT)
    }

    fun getRegisterSmsCode(v: View) {

        val coldDownButton = v as ColdDownTextView

        val userName = username.value


        if (!checkInput(userName, "手机号不能为空"))
            return

        restApi.getSms(SmsReq(userName!!).apply { setTypeRegisterV2() })
                .arrangeComplete(Action {
                    Toaster.message("验证码已发送")
                    coldDownButton.start()
                }, { errHandler(it) })
    }


    @SuppressLint("CheckResult")
    fun register() {

        val wifiManager = context.applicationContext.getSystemService(Context.WIFI_SERVICE) as WifiManager

        var wifiName = wifiManager.connectionInfo?.ssid ?: ""

        val userName = username.value ?: ""
        val sms = smsCode.value ?: ""
        restApi.registerV2(RegReq(userName, sms, code, deviceId).apply {
            wifi = wifiName
            get_token = 1
        })
                .arrange(Consumer { res ->

                    TokenManager.saveToken(res)
                    if (TextUtils.isEmpty(code)) {

                        //简单的手机号注册登录
                        context.quickStartActivity(WxLoginActivity::class.java) {
                            it.apply {
                                putExtra("bindMode", true)
//                                putExtra("code", res)
                                putExtra("token", res)
                                putExtra("deviceId", deviceId)
                            }
                        }

                    } else {
                        AppUtil.handleLogin(token = res)
                    }


                    context.suicideAfterTransition()

                }, {
                    errHandler(it)
                })

    }

   data class RegReq(var username: String, var vcode: String, var code: String, var deviceid: String) {

       var os_version = Build.VERSION.RELEASE
       var versionname = BuildConfig.VERSION_NAME
       var wifi = ""
       var model = Build.MODEL
       var get_token = 0

       var inviterid = TokenManager.channel()
   }

    fun finish() {
        context.suicideAfterTransition()
    }
}